package com.siqi.hr.common.mongo;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.siqi.hr.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;


/**
 *  获取MongoDB连接单例工具类
 *  @author  xiaogq
 */
public class MongoDBManager {

    private static Logger log = LoggerFactory.getLogger(MongoDBManager.class);

    //定义私有的构造方法
    private MongoDBManager(){}
    //定义私有的对象实例
    private static MongoDBManager instance = null;
    //提供公有的获取对象实例方法
    public static synchronized MongoDBManager getInstance(){
        return instance == null ? new MongoDBManager() : instance;
    }

    /**
     * @ author   xiaogq
     * 获取Mongo具体数据库连接
     * @throws Exception
     */
    public MongoDatabase getDB(String dbName) throws Exception {
		//集群配置
        //mongoClient = new MongoClient(Arrays.asList(new ServerAddress("10.205.68.57", 8700), new ServerAddress("10.205.68.15", 8700),new ServerAddress("10.205.69.13", 8700)), options);
		//mongoClient.setReadPreference(ReadPreference.secondaryPreferred())
        MongoDatabase db = null;
        MongoClient mongoClient = null;
        try {
            if(db == null){
                //通过用户名、密码验证是否可以访问该数据库的数据
                MongoCredential credential = MongoCredential.createCredential(Constants.LONGINNAME, dbName, Constants.PASSWORD.toCharArray());
                //通过ip地址与端口号验证是否可以连接MongoDB服务
                ServerAddress serverAddress = new ServerAddress(Constants.HOSTNAME, Constants.PORT);
                //设置连接MongoDB服务的等待超时时间为2分钟连接时间为500毫秒
                MongoClientOptions options =  MongoClientOptions.builder().maxWaitTime(1000 * 60 * 2).connectionsPerHost(500).build();
                //连接MongoDB客户端
                mongoClient = new MongoClient(serverAddress, Arrays.asList(credential),options);
                // 连接数据库,若没有,则新建
                db = mongoClient.getDatabase(dbName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return db;
    }

}
